import axios from 'axios'
import { Toast } from 'vant'

// 创建axios实例
const instance = axios.create({
  timeout: 10000,
  baseURL: process.env.NODE_ENV === 'development' ? '' : '', 
  headers: {
    get: {},
    post: {
      'content-type': 'application/x-www-form-urlencoded;chartset:UTF-8'
    }
  }
})

// 请求拦截
instance.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('token')
    token && (token === config.headers.authrization)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
instance.interceptors.response.use(
  res => {
    if (res.status === 200) {
      Promise.resolve(res)
    } else {
      Promise.reject(res)
    }
  },
  error => {
    if (error.response.status) {
      switch (error.response.status) {
        // 未登录
        case 401:
          router.replace({
            path: '/login',
            redirect: router.currentRoute.fullPath
          })
          break;
        // 登录失效
        case 403:
          Toast({message: '登录过期，请重新登录'})
          sessionStorage.removeItem('token')
          router.replace({
            path: '/login',
            redirect: router.currentRoute.fullPath
          })
          break;
        // ...
        default:
          break;
      }
    }
  }
)

// 设置请求方法
export function get(url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then(
      res => {
        resolve(res.data)
      },
      err => {
        reject(err)
      }
    ).catch(err => {
      reject(err)
    })
  })
}

export function post(url, params) {
  return new Promise((resolve, reject) => {
    instance.post(url, {
      params: params
    }).then(
      res => {
        resolve(res.data)
      },
      err => {
        reject(err)
      }
    ).catch(err => {
      reject(err)
    })
  })
}